package org.soft.xinyu.equipmentmanagement.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.soft.xinyu.equipmentmanagement.entity.MachineSubmachine;
import org.soft.xinyu.equipmentmanagement.entity.MachineTest;
import org.soft.xinyu.equipmentmanagement.entity.WswMachine;
import org.soft.xinyu.equipmentmanagement.result.Result;
import org.soft.xinyu.equipmentmanagement.service.MachineFileService;
import org.soft.xinyu.equipmentmanagement.service.MachineSubmachineService;
import org.soft.xinyu.equipmentmanagement.service.MachineTestService;
import org.soft.xinyu.equipmentmanagement.service.WswMachineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author vicente
 * @since 2021-11-22
 */
@RestController
@RequestMapping("/wsw-machine")
public class WswMachineController {

    @Autowired
    private WswMachineService wswMachineService;

    @Autowired
    private MachineSubmachineService machineSubmachineService;

    @Autowired
    private MachineTestService machineTestService;

    @Autowired
    private MachineFileService machineFileService;

    /**
     * 所有查询或者按条件查询并分页
     *
     * @param pageNum
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getWswMachineList")
    public Result<IPage<WswMachine>> getWswMachineList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                       @RequestParam(value = "machineName", required = false) String machineName,
                                                       @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) throws ParseException {
        IPage<WswMachine> page = wswMachineService.page(new Page<>(pageNum, pageSize),
                new QueryWrapper<WswMachine>()
                        .lambda()
                        .like(!"".equals(machineName) && machineName != null, WswMachine::getMachineName, machineName)
                        .orderByDesc(WswMachine::getCreateTime));

        //取时间
        Date date=new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        //把日期往前减少一天，若想把日期向后推一天则将负数改为正数
        calendar.add(Calendar.DATE,+15);
        date=calendar.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String startDate = formatter.format(date);

        List<WswMachine> records = page.getRecords();
        List<WswMachine> red = new ArrayList<>();
        Iterator iter = records.iterator();
        while (iter.hasNext()){
            WswMachine wswMachine = (WswMachine) iter.next();
            if (!ObjectUtils.isEmpty(wswMachine.getTermOfValidity())) {
                if (
                        wswMachine.getTermOfValidity().before(formatter.parse(startDate))
                ) {
                    red.add(wswMachine);
                    iter.remove();
                }
            }
        }
        for (WswMachine wswMachine : red) {
            wswMachine.setIdRed(true);
        }
        records.addAll(0, red);
        page.setRecords(records);
            return Result.success("请求成功", page);
    }

    /**
     * 删除设备记录以及附属设备以及上传的文件等
     *
     * @param id
     * @return
     */
    @DeleteMapping("/removeWswMachine/{id}")
    public Result<Boolean> removeWswMachine(@PathVariable int id) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("machine_id", id);
        //删除主设备信息
        wswMachineService.removeById(id);
        //删除附属设备信息
        machineSubmachineService.removeByMap(map);
        //删除主设备测定点信息
        machineTestService.removeByMap(map);
        return Result.success("请求成功", true);
    }

    /**
     * 新增设备信息以及设备文件等
     *
     * @param wswMachine
     * @return
     */
    @PostMapping("/addWswMachine")
    public Result<Boolean> addWswMachine(@RequestBody WswMachine wswMachine) {
        //新增设备记录
        boolean b = wswMachineService.save(wswMachine);
        if (!b) {
            return Result.success(false);
        }
        //测定点为1增加设备检定点信息
        if (wswMachine.getTestBool() == "1" || "1".equals(wswMachine.getTestBool())) {
            svMachineTest(wswMachine.getMachineTest(), wswMachine.getId().toString());
        }
        //增加附属设备信息
        if (wswMachine.getMachineSubmachines().size() > 0 && wswMachine.getMachineSubmachines() != null) {
            for (MachineSubmachine machineSubmachine : wswMachine.getMachineSubmachines()) {
                machineSubmachine.setMachineId(wswMachine.getId().toString());
                machineSubmachineService.save(machineSubmachine);
            }
        }
        return Result.success(true);
    }

    /**
     * 修改设备信息
     *
     * @param wswMachine
     * @return
     */
    @PutMapping("/updateWswMachine")
    public Result<Boolean> updateWswMachine(@RequestBody WswMachine wswMachine) {
        if (wswMachine.getId() == 0 || wswMachine.getId() == null) {
            return Result.success(false);
        }
        //修改主设备
        boolean b = wswMachineService.updateById(wswMachine);
        //判断检定点1修改 0删除记录
        if (wswMachine.getTestBool() == "1" || "1".equals(wswMachine.getTestBool())) {
            svMachineTest(wswMachine.getMachineTest(), wswMachine.getId().toString());
        } else if (wswMachine.getTestBool() == "0" || "0".equals(wswMachine.getTestBool())) {
            Map<String, Object> map = new HashMap<>(1);
            map.put("machine_id", wswMachine.getId());
            machineTestService.removeByMap(map);
        }
        //修改附属设备;先删除再增加
        machineSubmachineService.remove(new QueryWrapper<MachineSubmachine>().eq("machine_id", wswMachine.getId()));
        if (wswMachine.getMachineSubmachines().size() > 0 && wswMachine.getMachineSubmachines() != null) {
            for (MachineSubmachine machineSubmachine : wswMachine.getMachineSubmachines()) {
                machineSubmachine.setMachineId(wswMachine.getId().toString());
                machineSubmachineService.save(machineSubmachine);
            }
        }
        return Result.success(b);
    }

    /**
     * 查询单个设备信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getWswMachineById")
    public Result<WswMachine> updateWswMachine(@RequestParam int id) {
        WswMachine wswMachine = wswMachineService.getById(id);
        return Result.success(wswMachine);
    }

    /**
     * 打开文件夹（不存在则创建）
     *
     * @param name
     * @param id
     * @return
     */
    @GetMapping("/openLocalMakir")
    public Result<Boolean> openLocalMakir(@RequestParam String name, @RequestParam int id) {
        WswMachine wswMachine = wswMachineService.getById(id);
        File path = null;
        try {
            path = path = new File(ResourceUtils.getURL("classpath:").getPath());
            String p = wswMachine.getId() + "-" + wswMachine.getMachineId() + "-" + wswMachine.getMachineName();
            String newPath1 = path.getParentFile().getParentFile().getParent() + File.separator + "uploads" + File.separator + p + File.separator;
            makeMakir(newPath1);
            String newPath2 = path.getParentFile().getParentFile().getParent() + File.separator + "uploads" + File.separator;
            makeMakir(newPath2);
            String onlinePath = path.getParentFile().getParentFile().getParent() + File.separator + "uploads" + File.separator + p + File.separator + name + File.separator;
            makeMakir(onlinePath);
            //打开文件夹
            Runtime.getRuntime().exec("explorer.exe " + onlinePath);
//            Desktop.getDesktop().open(new File(onlinePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success(true);
    }

    private Boolean svMachineTest(MachineTest machineTest, String machineId) {
        machineTest.setMachineId(machineId);
        boolean b = machineTestService.saveOrUpdate(machineTest);
        return b;
    }

    private void makeMakir(String onlinePath) {
        File folder = new File(onlinePath);
        //文件夹不存在则船建文件夹
        if (!folder.exists() && !folder.isDirectory()) {
            folder.mkdirs();
        }
    }
}
